package problem01;

/**
 * 使用链表版
 * @author Administrator
 *
 * @param <T>
 */
public class Stack<T> {

	
	private Node head;
	private int size;
	public Stack(){
		head = new Node();
		head.setNext(null);
		size=0;
	}
	/**
	 * 弹出	
	 * @return
	 */
	public synchronized T pop(){
		Node node = head.getNext();
		if(node != null){
			head.setNext(node.getNext());
			size--;
			return node.getValue();
		}
		throw new RuntimeException("Stack is empty!");
	}
	/**
	 * 压栈
	 * @param t
	 * @return
	 */
	public synchronized T push(T t){
		head.setNext(new Node(t,head.next));
		size++;
		return t;
	}
	public boolean isEmpty(){
		return size==0;
	}
	/**
	 * 查看栈顶元素，并不弹出
	 * @return
	 */
	public T peek(){
		Node node = head.getNext();
		if(node != null){
			return node.getValue();
		}
		throw new RuntimeException("Stack is empty!");
	}
	/**
	 * 内部类-->节点
	 * @author Administrator
	 *
	 */
	class Node{
		T value;
		Node next;
		T getValue() {
			return value;
		}
		void setValue(T value) {
			this.value = value;
		}
		Node getNext() {
			return next;
		}
		void setNext(Node next) {
			this.next = next;
		}
		Node(T value) {
			this.value = value;
			this.next = null;
		}
		Node() {
		}
		Node(T value , Node next){
			this.value = value;
			this.next = next;
		}
	}
	public static void main(String[] args) {
		Stack<Integer> stack = new Stack<Integer>();
//		stack.pop();
		stack.push(1);
//		stack.pop();
		System.out.println(stack.pop());
		stack.push(2);
		stack.push(2);
		stack.push(5);
		System.out.println(stack.pop());
		System.out.println(stack.pop());
		System.out.println(stack.pop());
	}
}
